<template>
  <!-- 图片列表  -->
  <div id="imageList" class="imageList">
    <!-- 瀑布流布局组件 -->
    <Waterfall
      :list="(currentResourceList as any)"
      :width="110"
      :animationDelay="160"
      :breakpoints="{
        890: { rowPerView: 7 },
        780: { rowPerView: 6 },
        670: { rowPerView: 5 },
        560: { rowPerView: 4 },
        450: { rowPerView: 3 },
      }"
    >
      <template #item="{ item, index }">
        <ImageItem
          :key="item.id"
          :id="item.id"
          :serial="index"
          :path="config.sourceUrl + item.path"
          :time="item.deleteTime"
          :refreshList="() => getDeleteResources(true)"
          :previewSrcList="previewSrcList"
        />
      </template>
    </Waterfall>
  </div>
</template>

<script lang="tsx" setup>
import { ref, onMounted, watch, defineComponent } from 'vue'
import { Refresh, Download, Clock, DocumentCopy } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { Waterfall } from 'vue-waterfall-plugin-next'
import 'vue-waterfall-plugin-next/dist/style.css'
import styles from './recycle.module.less'
import {
  getDeleteResourcesApi,
  recoverResourcesApi,
} from '@/request/api/resource'
import config from '@/config/config'
import { throttle } from '@/utils/func'

//
// 分页栏相关变量
const page = ref(1)
const pageSize = ref(5)
const total = ref(0)
const setPage = (val: number) => (page.value = val)
// const setPageSize = (val: number) => (pageSize.value = val)

const currentResourceList = ref<ResourceItf[]>([])
// 预览的资源地址
const previewSrcList = ref<string[]>([])

watch(
  () => page.value,
  () => getDeleteResources()
)
watch(
  () => pageSize.value,
  () => getDeleteResources()
)

// 获取删除的资源
const getDeleteResources = async (refresh: boolean = false) => {
  if (refresh) {
    currentResourceList.value = []
    previewSrcList.value = []
    page.value = 1
  }

  const res = await getDeleteResourcesApi(pageSize.value, page.value)
  if (res.code !== 200) return ElMessage.error('获取资源列表失败')
  currentResourceList.value = [
    ...currentResourceList.value,
    ...res.data.records,
  ]
  total.value = res.data.total

  let pl = []
  res.data.records.filter((item) => pl.push(config.sourceUrl + item.path))
  previewSrcList.value = [...previewSrcList.value, ...pl]
}

// 节流函数
const throttleFunc = throttle(() => setPage(page.value + 1), 1000)
// 列表滚动自动加载
const initscroll = () => {
  let block = document.getElementById('imageList')
  block.addEventListener('scroll', () => {
    if (block.scrollTop > block.scrollHeight * 0.1) {
      if (currentResourceList.value.length >= total.value) return
      // const p = page.value + 1
      // setPage(p)
      throttleFunc()
    }
  })
}

onMounted(() => {
  getDeleteResources()
  initscroll()
})

//
//
// 图片项组件
const ImageItem = defineComponent({
  props: {
    id: { type: String, default: '' },
    path: { type: String, default: '' },
    time: { type: String, default: '' },
    serial: { type: Number, default: 0 },
    refreshList: { type: Function, default: null },
    previewSrcList: { type: Array, default: [] },
  },
  setup(props) {
    const myElementRef = ref<any>()
    const show = ref<boolean>(false)

    onMounted(() => {
      const element = myElementRef.value

      if (!element) return
      element.addEventListener('mouseenter', () => {
        show.value = true
      })
      element.addEventListener('mouseleave', () => {
        show.value = false
      })
    })

    // 复制图片路径
    const copyText = () => {
      navigator.clipboard
        .writeText(props.path)
        .then(() => ElMessage.success('复制地址成功'))
        .catch(() => ElMessage.error('复制地址失败'))
    }

    // 下载文件
    const downFile = () => (window as any).fileControll.downFile(props.path)

    // 恢复图片
    const recoverResources = async () => {
      const res = await recoverResourcesApi([props.id])
      if (res.code !== 200) return ElMessage.error('恢复失败！')
      ElMessage.success('恢复成功！')
      props.refreshList()
    }

    return () => (
      <div class={styles.imageItem} ref={myElementRef}>
        <div style="display:flex;justify-content: center">
          <el-image
            style="width: 90px; "
            src={props.path}
            fit="fill"
            preview-src-list={props.previewSrcList}
            preview-teleported={true}
            initial-index={props.serial}
            infinite={false}
            hide-on-click-modal={true}
          />
        </div>

        <div class={styles.serial}>{props.serial + 1}</div>

        {show.value ? (
          <div class={styles.btn}>
            <el-icon title="下载图片" onClick={downFile}>
              <Download />
            </el-icon>
            <el-icon title={`删除时间：${props.time}`}>
              <Clock />
            </el-icon>
            <el-icon title="复制图片地址" onClick={copyText}>
              <DocumentCopy />
            </el-icon>
          </div>
        ) : (
          <div class={styles.btn}></div>
        )}

        {show.value ? (
          <el-icon
            class={styles.recycleBtn}
            title="恢复"
            onClick={recoverResources}
          >
            <Refresh />
          </el-icon>
        ) : (
          ''
        )}
      </div>
    )
  },
})
</script>

<style lang="less">
.imageList {
  max-height: 100%;
  overflow: auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: center;
  align-content: flex-start;
}
</style>
